package com.boss.salary.controller;

import com.boss.api.dto.ApiResultDTO;
import com.boss.common.base.BasicinfoBaseController;
import com.boss.common.entity.PageDTO;
import com.boss.common.service.ICommonService;
import com.boss.common.util.PageUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.salary.entity.AgencyVerify;
import com.boss.salary.entity.OperrateLogs;
import com.boss.salary.entity.SalaryRental;
import com.boss.salary.service.IAgencyVerifyService;
import com.boss.salary.service.IOperrateLogsService;
import com.boss.salary.vo.unitReportVO;
import com.boss.sys.ca.user.dto.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/agencyVerifyController")
public class AgencyVerifyController extends BasicinfoBaseController {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(AgencySalaryController.class);

    @Autowired
    private IAgencyVerifyService iAgencyVerifyService;

    @Autowired
    private ICommonService iCommonService;

    @Autowired
    private IOperrateLogsService iOperrateLogsService;

    /**
     * 新增 机构上报审核状态表
     *
     * @param agencyVerify
     * @return
     */
    @PostMapping("/saveAgencyVerify")
    public ApiResultDTO saveAgencyVerify(@RequestBody AgencyVerify agencyVerify) {
        try {
            iAgencyVerifyService.saveAgencyVerify(agencyVerify);
            return ApiResultDTO.success(null, "保存成功");
        } catch (Exception e) {
            logger.error("新增 机构上报审核状态表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "新增 机构上报审核状态表数据发生异常");
        }
    }

    /**
     * 更新 机构上报审核状态表
     *
     * @param agencyVerify
     * @return
     */
    @PostMapping("/updateAgencyVerify")
    public ApiResultDTO updateAgencyVerify(@RequestHeader("tokenid") String tokenid,@RequestBody AgencyVerify agencyVerify) {
        try {
//            String tokenid = "97ddf29aa1d9942b4e05e01a24deebea";
            UserDTO userDto = getUser(tokenid);
            iAgencyVerifyService.updateAgencyVerify(userDto, agencyVerify);
            return ApiResultDTO.success(null, "更新成功");
        } catch (Exception e) {
            logger.error("更新 机构上报审核状态表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "更新 机构上报审核状态表数据发生异常");
        }
    }

    /**
     * 单位上报
     * @param agencyVerify
     * @return
     */
    @PostMapping("/reportUnitSalary")
    public ApiResultDTO reportUnitSalary(@RequestHeader("tokenid") String tokenid,
                                        @RequestBody AgencyVerify agencyVerify) {
        try {
            UserDTO userDto = getUser(tokenid);

            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("单位工资编报--单位工资编报--修改工资");



            iAgencyVerifyService.reportUnitSalary(userDto, agencyVerify);
            return ApiResultDTO.success(null, "上报成功");
        } catch (Exception e) {
            logger.error("单位上报发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "单位上报发生异常");
        }
    }

    /**
     * 单位撤销上报
     * @param agencyVerify
     * @return
     */
    @PostMapping("/reportRevokeUnitSalary")
    public ApiResultDTO reportRevokeUnitSalary(@RequestHeader("tokenid") String tokenid,
                                         @RequestBody AgencyVerify agencyVerify) {
        try {
            UserDTO userDto = getUser(tokenid);
            iAgencyVerifyService.reportRevokeUnitSalary(userDto, agencyVerify);
            return ApiResultDTO.success(null, "单位撤销上报成功");
        } catch (Exception e) {
            logger.error("单位撤销上报发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "单位撤销上报发生异常");
        }
    }

    /**
     * 单位退回上报
     * @param agencyVerify
     * @return
     */
    @PostMapping("/reportUnitSalaryBack")
    public ApiResultDTO reportUnitSalaryBack(@RequestHeader("tokenid") String tokenid,
                                             @RequestBody AgencyVerify agencyVerify) {
        try {
            UserDTO userDto = getUser(tokenid);
            iAgencyVerifyService.reportUnitSalaryBack(agencyVerify, userDto);
            return ApiResultDTO.success(null, "单位上报退回成功");
        } catch (Exception e) {
            logger.error("单位上报退回发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "单位上报退回成功");
        }
    }

    /**
     * 确认应发、实发工资
     * @param salaryRental
     * @return
     */
    @PostMapping("/updateSalaryVerify")
    public ApiResultDTO updateSalaryVerify(@RequestHeader("tokenid") String tokenid,
                                           @RequestBody SalaryRental salaryRental) {
        try {
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("财政审核--接收单位数据--接收");
            operrateLogs.setAgencyId(salaryRental.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            iAgencyVerifyService.updateSalaryVerify(userDto, salaryRental);

            return ApiResultDTO.success(null, "接收成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("接收发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE,"接收工资数据发生异常");
        }
    }

    /**
     * 撤销确认
     * @param salaryRental
     * @return
     */
    @PostMapping("/sendBackSalaryVerify")
    public ApiResultDTO sendBackSalaryVerify(@RequestHeader("tokenid") String tokenid,
                                             @RequestBody SalaryRental salaryRental){
        try {
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("财政审核--接收单位数据--撤销接收");
            operrateLogs.setAgencyId(salaryRental.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            iAgencyVerifyService.sendBackSalaryVerify(userDto, salaryRental);
            return ApiResultDTO.success(null, "撤销确认成功");
        } catch (Exception e) {
            logger.error("撤销确认应发、实发工资发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤销确认应发、实发工资发生异常");
        }
    }

    /**
     * 退回
     * @param salaryRental
     * @return
     */
    @PostMapping("/sendBackSalaryVerify1")
    public ApiResultDTO sendBackSalaryVerify1(@RequestHeader("tokenid") String tokenid,
                                              @RequestBody SalaryRental salaryRental){
        try {
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("财政审核--接收单位数据--退回");
            operrateLogs.setAgencyId(salaryRental.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            iAgencyVerifyService.sendBackSalaryVerify1(userDto, salaryRental);
            return ApiResultDTO.success(null, "退回成功");
        } catch (Exception e) {
            logger.error("退回异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }

    /**
     * 获取本月单位新增人数
     * @return
     */
    @GetMapping("/getAddPersonNumByAgencyId")
    public ApiResultDTO getAddPersonNumByAgencyId(@RequestParam(value = "agencyId") String agencyId) {
        try {
            int num = iAgencyVerifyService.getAddPersonNumByAgencyId(agencyId);
            return ApiResultDTO.success(num, "获取本月单位新增人数成功");
        } catch (Exception e) {
            logger.error("获取本月单位新增人数发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取本月单位新增人数发生异常");
        }
    }

    /**
     * 十三月工资：查询历史月份列表（12个月）
     * @return
     */
    @GetMapping("/queryHistoryMonthList")
    public ApiResultDTO queryHistoryMonthList(@RequestParam("agencyId") String agencyId){
        try {
            List<String> historyMonthList = iAgencyVerifyService.getHistoryMonthList(agencyId);
            return ApiResultDTO.success(historyMonthList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ApiResultDTO.error(ERROR_RSCODE, "查询数据异常");
        }
    }

    /**
     * 单位上报情况查询
     */
    @GetMapping("/queryUnitReportPage")
    public ApiResultDTO queryUnitReportPage(@RequestHeader("tokenid") String tokenid,
                                            @RequestParam("page") String page,
                                            @RequestParam("limit") String limit,
                                            @RequestParam("state") String state){
        try{
            UserDTO userDTO = getUser(tokenid);
            List<String> childrenId = iCommonService.getAgencyChildrenId(userDTO, "0");
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page, limit);
            PageDTO<unitReportVO> pageDTO = iAgencyVerifyService.getUnitReportPage(paginationDTO, state, childrenId, userDTO.getProvince());
            return ApiResultDTO.success(pageDTO);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }


    /**
     * 根据单位id获取审核信息
     * @param agencyId
     * @return
     */
    @GetMapping("/getAgencyVerifyByAgencyId/{agencyId}")
    public ApiResultDTO getAgencyVerifyByAgencyId(@PathVariable("agencyId") String agencyId) {
        try{
            AgencyVerify agencyVerify = iAgencyVerifyService.getAgencyVerifyByAgencyId(agencyId);
            return ApiResultDTO.success(agencyVerify);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取审核信息失败");
        }
    }

    /**
     * 根据单位id判断是否生成工资数据
     * @param agencyId
     * @return
     */
    @GetMapping("/getSalaryDataByAgencyId")
    public ApiResultDTO getSalaryDataByAgencyId(@RequestParam("agencyIds") List<String> agencyId) {
        try{
            boolean status = iAgencyVerifyService.getSalaryDataByAgencyId(agencyId);
            return ApiResultDTO.success(status);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, "根据单位id判断是否生成工资数据失败");
        }
    }

    /**
     * 校验是否存在重复人员
     * @return
     */
    @GetMapping("/selectOverlapPersionInfo")
    public ApiResultDTO selectOverlapPersionInfo(@RequestHeader("tokenid") String tokenid) {
        try{
            UserDTO userDTO = getUser(tokenid);
            List<Map<String, Object>> requestList= iAgencyVerifyService.selectOverlapPersionInfo(userDTO,null);
            if(CollectionUtils.isEmpty(requestList)){
                return ApiResultDTO.success(requestList,"未检测到重复人员信息");
            }
            return ApiResultDTO.success(requestList,"存在重复人员信息！请查看!");

        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, "检查失败");
        }
    }
    /**
     *查询人员调出未调入
     * @param tokenid

     * @return
     */
    @GetMapping("/getpersonTransferList")
    public ApiResultDTO getSalary(@RequestHeader("tokenid")String tokenid ){
        try {
            UserDTO userDTO = getUser(tokenid);
            String month= iAgencyVerifyService.currentYear(userDTO.getProvince());
            List<Map<String, Object>> requestList= iAgencyVerifyService.selectPersonTransfer(userDTO.getProvince(),month);
            if(CollectionUtils.isEmpty(requestList)){
                return ApiResultDTO.success(requestList,"未检测到有调出未调入人员");
            }
            return ApiResultDTO.success(requestList,"存在调出未调入人员！请查看!");
        } catch (Exception e) {
            logger.error("获取工资数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取工资数据发生异常");
        }
    }
}